package org.gavin.core.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jcajce.spec.SM2ParameterSpec;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Hex;

import java.io.IOException;
import java.math.BigInteger;
import java.security.*;

/**
 * @author: G1900008
 * @date: 2023/3/16 14:51
 */
public class Sm2Utils {
    private final static String PROVIDER_NAME = "BC";
    private final static int RS_LEN = 32;
    private static final X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");
    private static final ECDomainParameters ecDomainParameters =
            new ECDomainParameters(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());
    private static final ECParameterSpec ecParameterSpec =
            new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());

    static {
        if (Security.getProvider(PROVIDER_NAME) != null) {
            Security.removeProvider(PROVIDER_NAME);
        }
        Security.addProvider(new BouncyCastleProvider());
    }

    public static KeyPair generateKeyPair() {
        try {
            KeyPairGenerator kpGen = KeyPairGenerator.getInstance("EC", PROVIDER_NAME);
            kpGen.initialize(ecParameterSpec, new SecureRandom());
            KeyPair kp = kpGen.generateKeyPair();
            return kp;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String sign2Hex(String source, String userId, String privateKey) {
        byte[] bytes = signSm3WithSm2(
                source.getBytes(), userId.getBytes(), getPrivateKeyFromD(new BigInteger(privateKey)));
        return Hex.toHexString(bytes);
    }

    public static boolean verify4Hex(String source, String userId, String sign, String publicKey) {
        return verifySm3WithSm2(
                source.getBytes(), userId.getBytes(), Hex.decode(sign.getBytes()), getPublicKeyFromQ(publicKey));
    }

    public static String sign2Base64(String source, String userId, String privateKey) {
        byte[] bytes = signSm3WithSm2(
                source.getBytes(), userId.getBytes(), getPrivateKeyFromD(new BigInteger(privateKey)));
        return Base64.encode(bytes);
    }

    public static boolean verify4Base64(String source, String userId, String sign, String publicKey) {
        return verifySm3WithSm2(
                source.getBytes(), userId.getBytes(), Base64.decode(sign.getBytes()), getPublicKeyFromQ(publicKey));
    }

    public static byte[] signSm3WithSm2(byte[] msg, byte[] userId, PrivateKey privateKey) {
        return rsAsn1ToPlainByteArray(signSm3WithSm2Asn1Rs(msg, userId, privateKey));
    }

    /**
     * @param msg
     * @param userId
     * @param privateKey
     * @return rs in <b>asn1 format</b>
     */
    public static byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, PrivateKey privateKey) {
        try {
            SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
            Signature signer = Signature.getInstance("SM3withSM2", PROVIDER_NAME);
            signer.setParameter(parameterSpec);
            signer.initSign(privateKey, new SecureRandom());
            signer.update(msg, 0, msg.length);
            byte[] sig = signer.sign();
            return sig;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param msg
     * @param userId
     * @param rs        r||s，直接拼接byte数组的rs
     * @param publicKey
     * @return
     */
    public static boolean verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey) {
        if (rs == null || msg == null || userId == null) {
            return false;
        }
        if (rs.length != RS_LEN * 2) {
            return false;
        }
        return verifySm3WithSm2Asn1Rs(msg, userId, rsPlainByteArrayToAsn1(rs), publicKey);
    }

    /**
     * @param msg
     * @param userId
     * @param rs        in <b>asn1 format</b>
     * @param publicKey
     * @return
     */
    public static boolean verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] rs, PublicKey publicKey) {
        try {
            SM2ParameterSpec parameterSpec = new SM2ParameterSpec(userId);
            Signature verifier = Signature.getInstance("SM3withSM2", PROVIDER_NAME);
            verifier.setParameter(parameterSpec);
            verifier.initVerify(publicKey);
            verifier.update(msg, 0, msg.length);
            return verifier.verify(rs);
        } catch (Exception e) {
            //            throw new RuntimeException(e);
            return false;
        }
    }


    public static byte[] decrypt(byte[] data, PrivateKey key) {
        try {
            BCECPrivateKey localECPrivateKey = (BCECPrivateKey) key;
            ECPrivateKeyParameters ecPrivateKeyParameters =
                    new ECPrivateKeyParameters(localECPrivateKey.getD(), ecDomainParameters);
            SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
            sm2Engine.init(false, ecPrivateKeyParameters);
            try {
                return sm2Engine.processBlock(data, 0, data.length);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] encrypt(byte[] data, PublicKey key) {
        BCECPublicKey localECPublicKey = (BCECPublicKey) key;
        ECPublicKeyParameters ecPublicKeyParameters =
                new ECPublicKeyParameters(localECPublicKey.getQ(), ecDomainParameters);
        SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
        sm2Engine.init(true, new ParametersWithRandom(ecPublicKeyParameters, new SecureRandom()));
        try {
            return sm2Engine.processBlock(data, 0, data.length);
        } catch (InvalidCipherTextException e) {
            throw new RuntimeException(e);
        }
    }

    public static String encrypt2Hex(String text, String publicKey) {
        return Hex.toHexString(encrypt(text.getBytes(), getPublicKeyFromQ(publicKey))).substring(2);
    }

    public static String decrypt4Hex(String cipher, String privateKey) {
        BCECPrivateKey key = getPrivateKeyFromD(new BigInteger(privateKey));
        byte[] decode = Hex.decode("04" + cipher);
        byte[] bytes = decrypt(decode, key);
        return new String(bytes);
    }

    public static String encrypt2Base64(String text, String publicKey) {
        byte[] b1 = encrypt(text.getBytes(), getPublicKeyFromQ(publicKey));
        byte[] b2 = new byte[b1.length - 1];
        System.arraycopy(b1, 1, b2, 0, b1.length - 1);
        return Base64.encode(b2);
    }

    public static String decrypt4Base64(String cipher, String privateKey) {
        BCECPrivateKey key = getPrivateKeyFromD(new BigInteger(privateKey));
        String hexCipher = Hex.toHexString(Base64.decode(cipher));
        byte[] decode = Hex.decode("04" + hexCipher);
        byte[] bytes = decrypt(decode, key);
        return new String(bytes);
    }

    public static BCECPrivateKey getPrivateKeyFromD(BigInteger d) {
        ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(d, ecParameterSpec);
        return new BCECPrivateKey("EC", ecPrivateKeySpec, BouncyCastleProvider.CONFIGURATION);
    }

    public static BCECPublicKey getPublicKeyFromQ(String publicKey) {
        ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(
                x9ECParameters.getCurve().createPoint(
                        new BigInteger(publicKey.substring(0, 64), 16),
                        new BigInteger(publicKey.substring(64), 16)),
                ecParameterSpec
        );
        return new BCECPublicKey("EC", ecPublicKeySpec, BouncyCastleProvider.CONFIGURATION);
    }

    public static BCECPublicKey getPublicKeyFromXY(BigInteger x, BigInteger y) {
        ECPublicKeySpec ecPublicKeySpec =
                new ECPublicKeySpec(x9ECParameters.getCurve().createPoint(x, y), ecParameterSpec);
        return new BCECPublicKey("EC", ecPublicKeySpec, BouncyCastleProvider.CONFIGURATION);
    }

    /**
     * BC的SM3withSM2签名得到的结果的rs是asn1格式的，加密机需要直接拼接r||s的字节数组，使用这个方法转换
     *
     * @param rsDer rs in asn1 format
     * @return sign result in plain byte array
     */
    private static byte[] rsAsn1ToPlainByteArray(byte[] rsDer) {
        ASN1Sequence seq = ASN1Sequence.getInstance(rsDer);
        byte[] r = bigIntToFixeXLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
        byte[] s = bigIntToFixeXLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
        byte[] result = new byte[RS_LEN * 2];
        System.arraycopy(r, 0, result, 0, r.length);
        System.arraycopy(s, 0, result, RS_LEN, s.length);
        return result;
    }

    /**
     * BC的SM3withSM2验签需要的rs是asn1格式的，加密机返回的是r||s的字节数组，使用这个方法转化成asn1格式
     *
     * @param sign in plain byte array
     * @return rs result in asn1 format
     */
    private static byte[] rsPlainByteArrayToAsn1(byte[] sign) {
        if (sign.length != RS_LEN * 2) {
            throw new RuntimeException("err rs. ");
        }
        BigInteger r = new BigInteger(1, Arrays.copyOfRange(sign, 0, RS_LEN));
        BigInteger s = new BigInteger(1, Arrays.copyOfRange(sign, RS_LEN, RS_LEN * 2));
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(r));
        v.add(new ASN1Integer(s));
        try {
            return new DERSequence(v).getEncoded("DER");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] bigIntToFixeXLengthBytes(BigInteger rOrS) {
        // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
        // r and s are the result of mod n, so they should be less than n and have length<=32
        byte[] rs = rOrS.toByteArray();
        if (rs.length == RS_LEN) {
            return rs;
        } else if (rs.length == RS_LEN + 1 && rs[0] == 0) {
            return Arrays.copyOfRange(rs, 1, RS_LEN + 1);
        } else if (rs.length < RS_LEN) {
            byte[] result = new byte[RS_LEN];
            Arrays.fill(result, (byte) 0);
            System.arraycopy(rs, 0, result, RS_LEN - rs.length, rs.length);
            return result;
        } else {
            throw new RuntimeException("err rs: " + Hex.toHexString(rs));
        }
    }

    private static void genHeader() {
        String appId = "YTSD-T001";
        String appPriKey = "71305551703324484566075803649980287061049377777421305162896689122992234553338";
        String sysPubKey = "43D82ED83E1FA2DED52FC098353282077B4D3B788C6BE43C8CEF491766F495EE11C0774F62B5326E17805A6763CDB11BDD3243D3A01806FB4281C96EB604743B";
        String timestamp = System.currentTimeMillis() + "";
        JSONObject jHeader = new JSONObject();
        jHeader.put("appId", appId);
        jHeader.put("signatureIdType", "1");
        jHeader.put("signatureId", appId);
        jHeader.put("timestamp", timestamp);
        jHeader.put("signature", Sm2Utils.sign2Base64(timestamp, appId, appPriKey));
        System.out.println("gw-header : " +jHeader);
        String s1 = IdUtil.fastSimpleUUID();
        System.out.println(" S1 :"+ s1);
        System.out.println("content : "+Sm2Utils.encrypt2Base64(s1,sysPubKey));
    }

    public static void genKeyPair() {
        KeyPair kp1 = generateKeyPair();
        BigInteger d = ((BCECPrivateKey) kp1.getPrivate()).getD();
        byte[] encoded = ((ECPublicKey) kp1.getPublic()).getQ().getEncoded(false);
        System.out.println("私钥D:" + d);
        System.out.println("公钥Q：" + Hex.toHexString(encoded).toUpperCase().substring(2));
    }

    public static void main(String[] args) {
        //genKeyPair();
        genHeader();

        //System.out.println("SM2 BASE64:" + Sm2Utils.encrypt2Base64("d6c50989a5c7446b9ee8828b78a21d34", "43D82ED83E1FA2DED52FC098353282077B4D3B788C6BE43C8CEF491766F495EE11C0774F62B5326E17805A6763CDB11BDD3243D3A01806FB4281C96EB604743B"));
        if (true) return;


        String source = "ABC123";
        String userId = "ACE-T001";
        String privateKey = "71305551703324484566075803649980287061049377777421305162896689122992234553338";
        String publicKey = "1D07F8B51184E1D18F20CE08E4E0F6D580E794938CB3346267B2F6EB85A755789D90C6A9F03D566106332075569EA1E28DA4A91C12EE0117DC82BE4E8A8B08F3";
        String hexSign = sign2Hex(source, userId, privateKey);
        String base64Sign = sign2Base64(source, userId, privateKey);
        System.out.println("HEX SIGN: " + hexSign);
        System.out.println("VERIFY RESULT: " + verify4Hex(source, userId, hexSign, publicKey));
        System.out.println("BASE64 SIGN: " + base64Sign);
        System.out.println("VERIFY RESULT: " + verify4Base64(source, userId, base64Sign, publicKey));

        byte[] bytes = encrypt(source.getBytes(), getPublicKeyFromQ(publicKey));
        System.out.println(Hex.toHexString(bytes).substring(2));
        System.out.println(Base64.encode(Hex.decode(Hex.toHexString(bytes).substring(2))));

        byte[] bytes2 = new byte[bytes.length - 1];
        System.arraycopy(bytes, 1, bytes2, 0, bytes.length - 1);
        System.out.println(Hex.toHexString(bytes2));
        System.out.println(Base64.encode(bytes2));
        System.out.println(Base64.encode(bytes));


        String cipher = "ZRCyrd2Lv83dgu0ov5k/VLkOAVJNot8MS6iArqe6u0mOVaTUZ4MF3eqy/W7lXWwqHAPHoTmIgyzmgLjKPXSty4e4NrNkEg1n26pzpsmYkIwlqIbjiBD0Tpxj9ch+Q62/QHdeStXL";
        System.out.println(decrypt4Base64(cipher, privateKey));

    }


}
